package com.inight.ojcodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.io.Closeable;
import java.io.IOException;
import java.util.List;

/**
 * java 操作 docker
 */
public class DockerDemo {

    public static void main(String[] args) throws InterruptedException {
        // 获取默认的 docker client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();


        // 发送 ping 命令
        PingCmd pingCmd = dockerClient.pingCmd();
        pingCmd.exec();

        // 拉取镜像
        String image = "nginx:latest";
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
        // 一般都用 exec
        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                // super.onNext(item);
                System.out.println("拉去镜像: " + item.toString());
            }
        };

        pullImageCmd.exec(new PullImageResultCallback());


        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        CreateContainerResponse response = containerCmd
                .withCmd("echo", "Hello Docker!")
                .exec();
        System.out.println(response);
        String containerId = response.getId();


        // 查看容器状态
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        for (Container container : containerList) {
            System.out.println("容器: " + container);
        }

        // 启动容器. 没有返回值
        dockerClient.startContainerCmd(containerId).exec();

        // 查看日志.
        // 输出日志是分批的, 假如日志非常多, 不至于让线程卡死
        LogContainerCmd logContainerCmd = dockerClient.logContainerCmd(containerId);
        LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                System.out.println("日志: " + new String(item.getPayload()));
                super.onNext(item);
            }
        };
        logContainerCmd
                .withStdErr(true)
                .withStdOut(true)
                .exec(logContainerResultCallback)
                .awaitCompletion();  // 这一步不能少, 异步的. 可能不会有日志

        // 删除容器. withForce 强制删除容器
        dockerClient.removeContainerCmd(containerId).withForce(true).exec();

        // 删除镜像
        dockerClient.removeImageCmd(image).exec();


    }


}
